/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sfms.controller;
import sfms.util.MD5;
import sfms.model.*;

/**
 * Controller for the login window
 * @author amp942
 */
public class Login implements ControllerBase
{
    private sfms.view.Login view;
    private Model model;
    
    /**
     * Initialise a new LoginController object
     */
    public Login(Model m) {
        model = m;
        view = new sfms.view.Login(this);
    }
    
    @Override
    public void show() {
        view.setVisible(true);
    }
    
    @Override
    public void hide() {
        view.setVisible(false);
        view.dispose();
    }
    
    /**
     * Check the login credentials
     * @param username Supplied username
     * @param password Supplied password
     */
    public void checkLogin(String username, String password) {
        // hash the password and validate the login
        String hash = String.valueOf(MD5.encrypt(password.toCharArray()));
        User user = model.getUser(username, hash);

        if (user != null && user.isActive() == true)
        {
            if (User.CUSTOMER.equals(user.getRole())){
                new sfms.controller.Customer(model, user).show();
            }
            else if (User.STAFF.equals(user.getRole())){
                new sfms.controller.Staff(model, user).show();
            }
            else{
                new sfms.controller.Admin(model, user).show();
            }
            view.setVisible(false);
        }
        // Otherwise, display an alert and remain on login screen.
        view.showInvalid();
    }
}
